import express from 'express';
import mysql from 'mysql2/promise';
import cors from 'cors';
const app = express();
const port = 3000;

// 配置CORS
app.use(cors());
app.use(express.json());

// 创建数据库连接池
const pool = mysql.createPool({
  host: '112.124.8.108',
  user: 'chennz',
  password: 'Lancer@461379',
  database: 'project',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 测试数据库连接
pool.getConnection()
  .then(connection => {
    console.log('数据库连接成功');
    connection.release();
  })
  .catch(err => {
    console.error('数据库连接失败:', err);
  });

// API路由 - 获取所有店铺数据
app.get('/mysql/stores', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM store');
    res.json(rows);
  } catch (err) {
    console.error('获取店铺数据失败:', err);
    res.status(500).json({ error: '获取数据失败' });
  }
});

// API路由 - 添加新店铺
app.post('/mysql/stores', async (req, res) => {
  try {
    const { name, address, policeStation, locationType, status, type, latitude, longitude, photoName, createdTime, checkAction, tag } = req.body;
    const photoNameStr = Array.isArray(photoName) ? photoName.join(',') : (photoName || '');
    const [result] = await pool.query(
      'INSERT INTO store (name, address, policeStation, locationType, status, type, latitude, longitude, photoName, createdTime, checkAction, tag) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [name, address, policeStation, locationType, status, type, latitude, longitude, photoNameStr, createdTime, checkAction, tag]
    );
    res.json({ id: result.insertId, ...req.body });
  } catch (err) {
    console.error('添加店铺失败:', err);
    res.status(500).json({ error: '添加数据失败' });
  }
});

// API路由 - 更新店铺
app.put('/mysql/stores/:id', async (req, res) => {
  try {
    const { name, address, policeStation, locationType, status, type, latitude, longitude, photoName, createdTime, checkAction, tag } = req.body;
    const [result] = await pool.query(
      'UPDATE store SET name = ?, address = ?, policeStation = ?, locationType = ?, status = ?, type = ?, latitude = ?, longitude = ?, photoName = ?, createdTime = ?, checkAction = ?, tag = ? WHERE id = ?',
      [name, address, policeStation, locationType, status, type, latitude, longitude, photoName, createdTime, checkAction, tag, req.params.id]
    );
    res.json({ ...req.body, id: parseInt(req.params.id), photoName: photoName.split(',') });
  } catch (err) {
    console.error('更新店铺失败:', err);
    res.status(500).json({ error: '更新数据失败' });
  }
});

// API路由 - 删除店铺
app.delete('/mysql/stores/:id', async (req, res) => {
  try {
    await pool.query('DELETE FROM store WHERE id = ?', [req.params.id]);
    res.json({ success: true });
  } catch (err) {
    console.error('删除店铺失败:', err);
    res.status(500).json({ error: '删除数据失败' });
  }
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});